<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="default" @click="handleExport()">
          <Icon icon="i-ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <a-button type="default" @click="handlePrint()" v-auth="'wms:jh:pick:jhPickMain:edit'">
          <Icon icon="ant-design:printer-outlined" /> {{ t('拣货单打印') }}
        </a-button>
        <a-button type="default" @click="handleShdPrint()" v-auth="'wms:jh:pick:jhPickMain:edit'">
          <Icon icon="ant-design:printer-twotone" /> {{ t('出库单打印') }}
        </a-button>
        <Popconfirm placement="bottom" :title="t('是否确认拣货完成？')" @confirm="handleBatchOver">
          <a-button type="success" ghost v-auth="'wms:jh:pick:jhPickMain:edit'">
            <Icon icon="ant-design:check-outlined" /> {{ t('拣货完成') }}
          </a-button>
        </Popconfirm>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ djno: record.djno })">
          {{ record.djno }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <PrintModal @register="registerPrintModal" />
    <TableTabs @register="registerTableTabsDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="ViewsWmsJhPickJhPickMainList">
  import { unref, onMounted } from 'vue';
  import { Popconfirm } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    jhPickMainDelete,
    jhPickMainListData,
    jhPickMainBachOver,
    findOrderCodeList,
    findHandleCidsByJhMain,
    updatePrintCount
  } from '/@/api/wms/jh/pick/jhPickMain';
  import { useDrawer } from '/@/components/Drawer';
  import { companyTreeData } from '/@/api/sys/company';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import PrintModal from '/@/components/print/printModal.vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useUserStore } from '/@/store/modules/user';
  import { dateUtil } from '/@/utils/dateUtil';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import TableTabs from '/@/views/wms/jh/pick/jhPickMain/tableTabs/tableTabs.vue';
  const userStore = useUserStore();

  const { t } = useI18n('wms.jh.pick.jhPickMain');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  console.log(meta, router.currentRoute.value.query);
  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('拣货单主表管理'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('公司'),
        field: 'companyCode',
        fieldLabel: 'company.companyName',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          allowClear: true,
          immediate: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('拣货时间'),
        field: 'createDate',
        component: 'RangePicker',
        // component: 'DatePicker',
        // componentProps: {
        //   format: 'YYYY-MM-DD',
        //   showTime: false,
        //   valueFormat: 'YYYY-MM-DD',
        // },
      },
      // {
      //   label: t('拣货日期'),
      //   field: 'date',
      //   component: 'RangePicker',
      //   // component: 'DatePicker',
      //   // componentProps: {
      //   //   format: 'YYYY-MM-DD',
      //   //   showTime: false,
      //   //   valueFormat: 'YYYY-MM-DD',
      //   // },
      // },
      {
        label: t('拣货状态'),
        field: 'jhStatus',
        component: 'Select',
        componentProps: {
          dictType: 'jh_main_status',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('拣货方式'),
        field: 'type',
        component: 'Select',
        componentProps: {
          dictType: 'jh_type',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('拣货单号'),
        field: 'djno',
        component: 'Input',
      },
      {
        label: t('制单人名称'),
        field: 'createByName',
        component: 'Input',
      },
    ],
    fieldMapToTime: [['createDate', ['createDate_gte', 'createDate_lte']]],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('拣货单号'),
      dataIndex: 'djno',
      key: 'a.djno',
      sorter: true,
      width: 120,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('拣货时间'),
      dataIndex: 'createDate',
      key: 'a.create_date',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('拣货方式'),
      dataIndex: 'type',
      key: 'a.type',
      dictType: 'jh_type',
      sorter: true,
      width: 120,
      align: 'center',
    },

    {
      title: t('拣货状态'),
      dataIndex: 'jhStatus',
      key: 'a.jh_status',
      dictType: 'jh_main_status',
      sorter: true,
      width: 130,
      align: 'center',
      fixed: 'right',
    },

    {
      title: t('拣货总数'),
      dataIndex: 'sumQty',
      key: 'a.sum_qty',
      sorter: true,
      width: 90,
      align: 'center',
    },
    {
      title: t('累计拣货'),
      dataIndex: 'sumPickQty',
      key: 'a.sum_pick_qty',
      sorter: true,
      width: 90,
      align: 'center',
    },
    {
      title: t('打印次数'),
      dataIndex: 'printCount',
      key: 'a.print_count',
      sorter: true,
      width: 90,
      align: 'center',
    },
    {
      title: t('公司编码'),
      dataIndex: 'companyCode',
      key: 'a.company_code',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('公司名称'),
      dataIndex: 'company.companyName',
      key: 'company.company_name',
      sorter: true,
      width: 200,
      align: 'left',
    },
    {
      title: t('操作人'),
      dataIndex: 'createByName',
      key: 'a.create_by_name',
      sorter: true,
      width: 130,
      align: 'center',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑拣货单主表'),
        onClick: handleForm.bind(this, { djno: record.djno }),
        auth: 'wms:jh:pick:jhPickMain:edit',
        ifShow: () => record.jhStatus == '0',
      },
      // {
      //   icon: 'i-ant-design:delete-outlined',
      //   color: 'error',
      //   title: t('删除'),
      //   onClick: handleview.bind(this, record),
      //   auth: 'wms:jh:pick:jhPickMain:edit',
      // },
      {
        icon: 'i-ant-design:delete-outlined',
        color: 'error',
        title: t('删除拣货单主表'),
        popConfirm: {
          title: t('是否确认删除拣货单主表'),
          confirm: handleDelete.bind(this, record),
        },
        auth: 'wms:jh:pick:jhPickMain:edit',
        ifShow: () => record.jhStatus == '0',
      },
    ],
  };

  const [registerTableTabsDrawer, { openDrawer: openTableTabsDrawer }] = useDrawer();
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getSelectRowKeys, getForm, setProps }] = useTable({
    api: jhPickMainListData,
    beforeFetch: (params) => {
      // params.jhStatus = 0;
      console.log(meta);
      meta.jhStatus ? params.jhStatus = meta.jhStatus : '';
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    immediate: false,
    rowSelection: {
      type: 'checkbox',
    },
  });

  

  async function handleview(record: Recordable) {
    const res = await findHandleCidsByJhMain({ djno: record.djno });
    let selIds = res.data.join(',');
    openTableTabsDrawer(true, {selIds});
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/wms/jh/pick/jhPickMain/exportData',
      params: getForm().getFieldsValue(),
    });
  }

  async function handleDelete(record: Recordable) {
    const params = { djno: record.djno };
    const res = await jhPickMainDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  // 打印
  async function handlePrint() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length == 0) {
      showMessage(t('请先选择数据'));
      return;
    }
    let params = {
      ids: arr.join(','),
      title: '拣货单打印',
      height: '0.9',
      width: '0.9',
      fileName: '拣货单',
    };
    openPrintModal(true, params);
    await updatePrintCount({selIds:arr.join(',')});
    await handleSuccess();
  }

  // 拣货完成
  async function handleBatchOver() {
    if (getSelectRowKeys().length) {
      const res = await jhPickMainBachOver({ selIds: getSelectRowKeys().join(',') });
      showMessage(res.message);
      handleSuccess({});
    } else {
      showMessage('请先选择一条数据');
    }
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  onMounted(async () => {
    setProps()
    handleCompany();
    getHomePage();
  });

  async function handleCompany() {
    let date = dateUtil(new Date()).format('YYYY-MM-DD')
    let arr = [date,date]
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
      createDate:arr
    });
    reload();
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
      createDate:arr
    });
  }

  async function getHomePage() {
    let date = dateUtil(new Date()).format('YYYY-MM-DD')
    let arr = [date, date];
    if (router.currentRoute.value.query.homePage == 'true'){
      await getForm().setFieldsValue({
        jhStatus: 0,
        createDate: '',
      });
      reload();
    }

    if (router.currentRoute.value.query.homePage == 'true1'){
      await getForm().setFieldsValue({
        createDate: arr,
      });
      reload();
    }

    if (router.currentRoute.value.query.homePage == 'true2'){
      await getForm().setFieldsValue({
        jhStatus: 2,
        createDate: arr,
      });
      reload();
    }
  }

  async function handleShdPrint() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length == 0) {
      showMessage(t('请先选择数据'));
      return;
    }
    // let newArr = arr.map(item=>{
    //   return item.djno
    // })
    const res = await findOrderCodeList({ selIds: getSelectRowKeys().join(',') });
    let params = {
      ids: res.data.join(','),
      title: '出库单打印',
      height: '0.9',
      width: '0.9',
      fileName: '出库单',
    };
    openPrintModal(true, params);
  }
</script>
